package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @FileName: FileServiceImpl
 * @Author Steven
 * @Date: 2021/8/10
 */
@Service
public class FileServiceImpl implements FileService{

    @Override
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        try {
            OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            //获取文件上传流
            InputStream inputStream=file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成唯一随机值
            String uuid= UUID.randomUUID().toString().replace("-","");
            fileName=uuid+fileName;
            String timeUrl=new DateTime().toString("yyyy/mm/dd");
            fileName=timeUrl+"/"+fileName;
            ossClient.putObject(bucketName,fileName,inputStream);
            //关闭oss
            ossClient.shutdown();
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
